package com.lrs.java.jdbc.pool;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

public class TestJDBCPool implements DataSource{
	public static TestJDBCPool pool = null;
	static List<EasyConnection> conns = new ArrayList<EasyConnection>();
	
	static {
		init();
	}
	
	static void init() {
		for(int i=0; i<20; i++) {
			EasyConnection easyConn = DBConnet();
			conns.add(easyConn);
		}	
	}
	
	private static EasyConnection DBConnet() {
		Connection conn = null;
		try {
			//Class.forName("oracle.jdbc.driver.OracleDriver");
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		}
		try {
			//conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:ZLPD", "scott", "tiger");
			conn = DriverManager.getConnection("jdbc:mysql://localhost/bbs", "root", "root");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		EasyConnection easyConn = new EasyConnection(conn);
		return easyConn;
		
	}

	private TestJDBCPool() {}
	
	public static TestJDBCPool getInstance() {
		if(pool == null) {
			pool = new TestJDBCPool();
		}
		return pool;
	}
	public Connection getConnection() throws SQLException {
		for(int i=0; i<conns.size(); i++) {
			EasyConnection ec  = conns.get(i);
			if(!ec.isBusy()) {
				ec.setBusy(true);
				return ec;
			}
		}
		return null;
	}

	public Connection getConnection(String username, String password)
			throws SQLException {
		return this.getConnection();
		
	}

	public int getLoginTimeout() throws SQLException {
		// TODO Auto-generated method stub
		return 0;
	}

	public PrintWriter getLogWriter() throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	public void setLoginTimeout(int arg0) throws SQLException {
		// TODO Auto-generated method stub
		
	}

	public void setLogWriter(PrintWriter arg0) throws SQLException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public <T> T unwrap(Class<T> iface) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean isWrapperFor(Class<?> iface) throws SQLException {
		// TODO Auto-generated method stub
		return false;
	}
	
	
}
